#!/usr/bin/python3
import subprocess
import time
from unittest import result



def Submitjob(pkgname) :
    firstcode=pkgname[0].lower()
    commandnew=subprocess.run(["submit","repoaddr.yaml","queue=vm-2p8g-rpmbuild","repo_addr="+REPO_ADDR+firstcode+"/"+pkgname],stdout=subprocess.PIPE,encoding="utf-8")

    jobid=commandnew.stdout.split()[len(commandnew.stdout.split())-1][3:]
    

    return jobid


def Touchtmpfile():
     #生成临时文件：

    #查询
    subprocess_1_="""#!/bin/sh
result=$(cci search -i jobs -d '{"_source": ["id", "job_stage","job_health"],"size":30000}'|grep $1)
echo $result
"""
    subprocess_1_file=open("subprocess_1_.sh","w")
    subprocess_1_file.write(subprocess_1_)
    subprocess_1_file.close



    repoaddr_yaml="""suite: rpmbuild
category: functional
rpmbuild:
custom_repo_name: compatible/f36
mount_repo_addr: https://api.compass-ci.openeuler.org:20018/rpm/testing/openeuler-22.03-LTS/compatible/f36/x86_64
mount_repo_name: compatible/f36
testbox: vm-2p8g
os: openeuler
os_version: 22.03-LTS
arch: x86_64
"""
    repoaddr_yaml_file=open("repoaddr.yaml","w")
    repoaddr_yaml_file.write(repoaddr_yaml)
    repoaddr_yaml_file.close()

    return 


def Rmtmpfile():
    subprocess.run(["rm","subprocess_1_.sh","repoaddr.yaml"])
    return 


FEDORA_VERSION="36"
REPO_ADDR=REPO_ADDR="https://mirrors.163.com/fedora/releases/"+FEDORA_VERSION+"/Everything/source/tree/Packages/"

if __name__ == "__main__":
    print("用法:将此脚本与包名list放置在同一目录下,执行脚本,当前指定repo源的fedora版本:",FEDORA_VERSION)
    #WORK_DIR=subprocess.run(["pwd"],stdout=subprocess.PIPE,encoding="utf-8").stdout

    print("输入列表全名:")
    #=input()
    listname=input().strip()
    try:
        listfile=open(listname,"r")
    except:
        print("列表名出现错误")



    pkglist=[]
    for i in listfile.readlines() :
        if i.strip() !="":
            pkglist.append(i.strip())

    #print("指定提交间隔:")
    #INTERNAL=input()

    print("最大并行任务数:")
    try :
        MAX_JOB=int(input())
    except:
        print("输入错误")
    
    Touchtmpfile()


    submiting_list=[]
    
    resultfile=open("resultlist","w")
    HEAD=-1

    
    while(True):

        if len(submiting_list)<MAX_JOB and HEAD<len(pkglist)-1:
            for i in range(MAX_JOB-len(submiting_list)):
                if HEAD<len(pkglist)-1:
                    HEAD=HEAD+1

                    submiting_list.append((HEAD,Submitjob(pkglist[HEAD])))
                    print("----提交新Job:",submiting_list[len(submiting_list)-1][1],pkglist[HEAD])




        print("\n查询中...")
        position=0
        for searchtime in range(len(submiting_list)):
            command=subprocess.run(["sh","subprocess_1_.sh",submiting_list[position][1]],stdout=subprocess.PIPE,encoding="utf-8")
            jobinfo=command.stdout.split()
            submiting_list[position][0]
            print(jobinfo[0],jobinfo[1],pkglist[submiting_list[position][0]])

            if jobinfo[1]=="submit" :
                resultfile.write(pkglist[submiting_list[position][0]]+(100-len(pkglist[submiting_list[position][0]]))*" "+jobinfo[1]+(20-len(jobinfo[1]))*" "+submiting_list[position][1]+"\n")
                submiting_list.pop(position)

            elif jobinfo[1]=="finish" :
                resultfile.write(pkglist[submiting_list[position][0]]+(100-len(pkglist[submiting_list[position][0]]))*" "+jobinfo[2]+(20-len(jobinfo[2]))*" "+submiting_list[position][1]+"\n")
                submiting_list.pop(position)
            else :
                position=position+1




        if len(submiting_list)==0 and HEAD==len(pkglist)-1:
            print("所有任务完成,输出至result文件")
            break

            


        print("当前进度:"+str(HEAD-len(submiting_list)+1)+"/"+str(len(pkglist))+" 正在进行的JOB:"+str(len(submiting_list)))

        time.sleep(3)

    resultfile.close()

    Rmtmpfile()
    #end



        






